
#! /usr/bin/python

import sys
import os
import time
import random
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
     #   self.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1","Tipo":"Italiano","Calle":"lacalle"}]



    def _process(self):
	 pass
class MyOrganization(Bureaucracy.Bureaucracy):
    def _process(self):
	    time.sleep(2000)

class MyUnit(Unit.Hierarchy):
    def onStart(self):
        time.sleep(10)
        template = Behaviour.ACLTemplate()
        template.setProperty("from",self.name)
        template.setPerformative("inform")
        template.setOntology("spade:x:unit")
        t = Behaviour.MessageTemplate(template)
        self.gotoBehaviour=self.GotoBehaviour(self)
        self.myAgent.addBehaviour(self.gotoBehaviour, t)

    class GotoBehaviour(Behaviour.Behaviour):
        def __init__(self,unit):
            self.unit=unit
            Behaviour.Behaviour.__init__(self)

        def _process(self):
            m= self._receive(True)
            if m and m.getProperty("from")==self.unit.name:
                unitName=m.getContent().split(":")[1]
                u=MyUnit(self.myAgent, nick=self.myAgent.nick, password="pass", name=unitName)
                print "Soy ",self.myAgent.getAID().getName(),"Dentro de la unidad:",self.unit.name,"Tratando de entrar en ",unitName
                d=[{"name":"rol","value":"fuentes de informacion"},{"name":"tipo","value":["Restaurant",self.myAgent.info[0]["Tipo"],self.myAgent.info[0]["Subtipo"]]}]
                entry=self.unit.requestEntryUnit(unitName,d)
                while not entry:
                   entry=self.unit.requestEntryUnit(unitName,d)
                if entry:
                    self.unit.joinUnit(u)
                    self.myAgent.removeBehaviour(self)

    def _process(self):
            print "Dentro de la unidad:"+self.name
            time.sleep(100)
            """mens=self.receiveMessage()
            while not mens and self.state!="unavailable":
              mens=self.receiveMessage()
            content=[]
            if mens:
                print mens
                for i in self.myAgent.info:
                    recurso=mens.getContent().split(":")[0]
                    tipo=mens.getContent().split(":")[1]
                    print recurso,tipo
                    if i["Tipo"]==tipo and recurso==i["Recurso"]:
                        content.append(i)
                if content==[]:
                    content=""
                ans=ACLMessage.ACLMessage()
                ans.setPerformative("inform")
                ans.setSender(self.myAgent.getAID())
                ans.addReceiver(mens.getSender())
                ans.setContent(str(content))
                ans.setConversationId(mens.getConversationId())
                self.sendPrivateMessage(ans,mens.getSender().getName())
                print "Soy ",self.myAgent.getAID().getName()," envio a ",ans.getReceivers()[0].getName()," la respuesta ",ans
"""


if __name__ == "__main__":
    a="sitea"
    if len(sys.argv)>1:
        max=sys.argv[1]
    else: max=5
    max=int(max)+1
    for n in xrange(1,max):
        agent = a+str(n)+"@apolo.dsic.upv.es"
        #agent = "agent@thx1138.dsic.upv.es"
        #agent = "agent@tatooine.dsic.upv.es"
        b = Example(agent,"pasword")
        l=["Italiano","Chino","Japones"]
        aux=[["Buffet","Menu"],["Vegetariano","Normal"],["Centrico","Afueras"]]
        i=random.randint(0,2)
        j=random.randint(0,1)
        print "Tipo:",l[i]," Subtipo:",aux[i][j]
        b.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1"+str(n),"Tipo":l[i],"Subtipo":aux[i][j],"Calle":"lacalleA"+str(n)}]
        b.nick=nick="fuenteA"+str(n)
        b.start()
        print "Agent "+agent+" registering"
        time.sleep(2)
        lista= b.getOrganizationList()
        print lista
        for i in lista:
            goal=b.getOrganizationInfo(i)["goal"]
            g=eval(goal)
            if g.has_key("necesita") and g["necesita"]=="fuentes de informacion turistica":
                o=MyOrganization(b,nick="fuenteA"+str(n), name=i)
                b.joinOrganization(o)
                l=o.getUnitList()
                print l
                for u in l:
                    info=o.getUnitInfo(u)
                    if info["type"]=="Hierarchy" and eval(info["goal"])["necesita"]=="fuentes de informacion":
                        unit=MyUnit(b, nick="fuenteA"+str(n), password="pass", name=u)
                        d=[{"name":"rol","value":"fuentes de informacion"},{"name":"tipo","value":["Restaurant",b.info[0]["Tipo"],b.info[0]["Subtipo"]]}]
                        entry=o.requestEntryUnit(u,d)
                        if not entry:
                           entry=o.requestEntryUnit(u,d)
                        if entry:
                            o.joinUnit(unit)







